import {defineStore} from 'pinia'
import {ref, computed} from 'vue'
import {
    addCartItem,
    getCartItems,
    removeCartItem,
    updateAllCartSelected,
    updateCartItemQuantity,
    updateCartItemSelected
} from "@/api/cart.js";

export const useCartStore = defineStore('cart', () => {
    // 使用 ref 替代 state
    const items = ref([])

    const initCart = async () => {
        const {data} = await getCartItems()
        items.value = data.map(item => {
            return {
                ...item,
                selected: item.selected === 1,
                image: item['product'].image,
                name: item['product'].name,
                description: item['product'].description,
                price: item['product'].price
            }
        })
    }
    // 使用 computed 计算总价
    const total = computed(() =>
        items.value.reduce((sum, item) => sum + (item.price * item.quantity), 0)
    )

    // 添加商品到购物车
    const addToCart = async (productId) => {
        return await addCartItem(productId)
    }

    // 从购物车移除商品
    const removeFromCart = async (productId) => {
        return await removeCartItem(productId);
    }

    // 更新商品数量
    const updateQuantity = async (productId, quantity) => {
        await updateCartItemQuantity(productId, quantity)
        const item = items.value.find(item => item.id === productId)
        if (item) {
            item.quantity = quantity
        }
    }

    // 更新商品选中状态
    const updateSelected = async (productId, selected) => {
        return await updateCartItemSelected(productId, selected)
    }

    // 更新所有商品的选中状态
    const updateAllSelected = async (selected) => {
        return await updateAllCartSelected(selected)
    }

    // 获取选中商品数量
    const selectedCount = computed(() => items.value.filter(item => item.selected).length)

    // 获取选中商品总价
    const selectedTotal = computed(() =>
        items.value
            .filter(item => item.selected)
            .reduce((sum, item) => sum + (item.price * item.quantity), 0)
    )

    return {
        items,
        total,
        initCart,
        selectedCount,
        selectedTotal,
        addToCart,
        removeFromCart,
        updateQuantity,
        updateSelected,
        updateAllSelected,
    }
})
